<?php
/**
 * Created by PhpStorm.
 * User: Mio
 * Date: 2017/10/13
 * Time: 11:32
 */

namespace app\index\model;


use think\Model;

class UserChannelRank extends Model
{

    //增加用户所在频道的经验值，并判断是否可升级
    public function addExp($user_id, $channel_id, $exp_num){
        $where = 'user_id ='.$user_id. ' and channel_id ='.$channel_id;
//        var_dump($where);

        $user_channel_rank = $this->getUserChannelRankInfo($where);
        if(empty($user_channel_rank)){
            $data = array(
                'user_id' => $user_id,
                'channel_id' => $channel_id,
            );
            $this->save($data);
            $user_channel_rank['exp'] = 0;
        }
//        var_dump($user_channel_rank);
        //获取下一等级
        $next_rank = $this->getUserNextChannelRank($user_id, $channel_id);
//        var_dump($exp_num,$where);
        $exp_num = intval($exp_num);
        $r = $this->where($where)->setInc('exp', $exp_num);
//        var_dump($r,$next_rank);
        if($r && $next_rank){

            //用户当前经验是否可升级
            $exp = $user_channel_rank['exp'] + $exp_num;
//            var_dump($exp,$next_rank['need_exp']);
            if($exp >= $next_rank['need_exp']){
//                var_dump($where);
                $this->where($where)->setField(array('channel_rank_id' => $next_rank['channel_rank_id']));
            }
        }
        return $r;
    }

    public function getUserChannelRankInfo($where){
        $r = $this->where($where)->find();
        if(empty($r)){
            return null;
        }else{
            return $r->toArray();
        }
    }


    //获取用户下一等级
    public function getUserNextChannelRank($user_id, $channel_id){
        $where = 'user_id ='.$user_id. ' and channel_id ='.$channel_id;
        $user_rank = $this->getUserChannelRankInfo($where);
        $user_exp = intval($user_rank['exp']);
        $next_rank = model('ChannelRank')->gitExp($user_exp);
//        var_dump($next_rank);
        return $next_rank;

    }

    public function addUserChannelRank($arr){
        return $this->add($arr);
    }
}